import { useEffect, useState } from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { Navigate } from 'react-router-dom';
import { Spin, message } from 'antd';
import { validateToken } from '@/api/auth'; // 需自行创建验证接口

// token 校验
const AuthWrapper = ({ children, validate = true }) => {
    const [isValidating, setIsValidating] = useState(true);
    const { token } = useSelector((state) => state.auth);
    const dispatch = useDispatch();

    useEffect(() => {
        if (!validate && !token) {
            message.error('请先登录！');
        }
    }, [token]);

    useEffect(() => {
        const checkToken = async () => {
            if (validate) {
                try {
                    const res = await validateToken(token);
                    if (!res.data?.valid) {
                        message.error('登录已过期，请重新登录');
                        // dispatch({ type: 'auth/logout' });
                    }
                } catch (error) {
                    message.error('验证失败，请重新登录');
                    console.error('Token验证失败:', error);
                    // dispatch({ type: 'auth/logout' });
                } finally {
                    setIsValidating(false);
                }
            } else {
                setIsValidating(false);
            }
        };

        if (token) {
            checkToken();
        } else {
            setIsValidating(false);
        }
    }, [token, dispatch, validate]);

    if (isValidating) {
        return <Spin size="large" fullscreen />;
    }

    return token ? children : <Navigate to="/auth/login" replace />;
};

export default AuthWrapper;
